package com.example.logindemo.service.impl;

import com.example.logindemo.service.FileUploadService;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

@Service
public class FileUploadServiceImpl implements FileUploadService {

    private final Path fileStorageLocation;

    public FileUploadServiceImpl() {
        // 使用项目根目录下的uploads文件夹作为文件存储位置
        this.fileStorageLocation = Paths.get("uploads").toAbsolutePath().normalize();

        // 创建上传目录（如果不存在）
        try {
            Files.createDirectories(this.fileStorageLocation);
        } catch (Exception ex) {
            throw new RuntimeException("无法创建上传文件的目录!", ex);
        }
    }

    @Override
    public String storeFile(MultipartFile file) {
        // 获取原始文件名
        String fileName = StringUtils.cleanPath(file.getOriginalFilename());

        try {
            // 检查文件名是否包含无效字符
            if (fileName.contains("..")) {
                throw new RuntimeException("文件名包含无效路径序列: " + fileName);
            }

            // 生成唯一文件名
            String uniqueFileName = UUID.randomUUID().toString() + "_" + fileName;

            // 复制文件到目标位置
            Path targetLocation = this.fileStorageLocation.resolve(uniqueFileName);
            Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);

            return uniqueFileName;
        } catch (IOException ex) {
            throw new RuntimeException("无法存储文件: " + fileName, ex);
        }
    }

    @Override
    public String getFileDownloadUri(String fileName) {
        return "/api/files/download/" + fileName;
    }
    
    @Override
    public String getFilePreviewUri(String fileName) {
        return "/api/files/" + fileName;
    }
    
    @Override
    public Resource loadFileAsResource(String fileName) {
        try {
            Path filePath = this.fileStorageLocation.resolve(fileName).normalize();
            Resource resource = new UrlResource(filePath.toUri());
            
            if (resource.exists()) {
                return resource;
            } else {
                throw new RuntimeException("文件未找到: " + fileName);
            }
        } catch (Exception ex) {
            throw new RuntimeException("文件加载失败: " + fileName, ex);
        }
    }
    
    @Override
    public boolean deleteFile(String fileName) {
        try {
            Path filePath = this.fileStorageLocation.resolve(fileName).normalize();
            return Files.deleteIfExists(filePath);
        } catch (IOException ex) {
            throw new RuntimeException("文件删除失败: " + fileName, ex);
        }
    }
}